package com.example.ch05_springboot_web.interceptors;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.time.Duration;
import java.time.LocalDateTime;

// 拦截器
public class TimeInterceptor implements HandlerInterceptor {

    LocalDateTime begin;

    Logger logger = LoggerFactory.getLogger(TimeInterceptor.class);

    @Override
    // 请求之前
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        begin = LocalDateTime.now();
        logger.info("当前请求"+request.getRequestURI()+"开始时间："+begin);
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    // 请求之后
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LocalDateTime end = LocalDateTime.now();
        // 计算两个时间差
        Duration duration = Duration.between(begin, end);
        // 获得相差的毫秒
        long mills = duration.toMillis();
        logger.info("当前请求"+request.getRequestURI()+"当前请求耗时："+mills);

        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
